<template>
	<view class="centerbox">
		<view class="rechTop">
			<view class="imgTitele flex">
				<image src="/static/images/toptitleImage.png"></image>
			</view>
			<view class="ChooseTitle">
				<view class="Vertical"></view>
				<span>店铺选择</span>
			</view>
			<view class="Store">
				<scroll-view class="scroll-container" scroll-x="true" show-scrollbar="false" enhanced>
					<view class="store-list">
						<view class="Storefront" v-for="(item, index) in Shoplist" :key="item"
							:class="{ 'selected': selectedStore === index }" @click="selectStore(item,index)">
							<view class="Store_right">
								<span class="store-name">{{item.shop_name}}</span>
								<button
									:class="['custom-shadow', selectedStore === index ? 'selected-btn' : '']">选择</button>
							</view>
							<view class="Store_left">
								<img
									:src="selectedStore === index ? '/static/images/Store_left.png' : '/static/images/baise.png'" />
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="tabClss">
				<wd-tabs v-model="eventChild" @change="handleChange">
					<block v-for="item in tabs" :key="item">
						<wd-tab :title="`${item}`">
							<view class="boxType" v-for="item in Machine" :key="item">
								<view class="boxType_left">
									<img v-if="!shouldShowGif(item)" src="/static/images/xiyiji.png" />
									<img v-else-if="isDryer(item) && !isAvailable(item)"
										src="/static/images/Hggif.gif" />
									<img v-else-if="isWasher(item) && !isAvailable(item)"
										src="/static/images/Xtgif.gif" />
									<view class="left_title">
										<p>{{item.device_name}}</p>
										<span v-if="!isAvailable(item)">
											<img src="/static/images/timeimg.png" />
											<span class="spleft">{{formatCountdown(item)}}</span>
										</span>
									</view>
								</view>
								<view class="boxType_right">
									<button :class="{'available': isAvailable(item), 'in-use': !isAvailable(item)}"
										:disabled="!isAvailable(item)">
										{{ isAvailable(item) ? '可使用' : '运转中' }}
									</button>
								</view>
							</view>
						</wd-tab>
					</block>
				</wd-tabs>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, reactive } from 'vue'
	import { httpGet, httpPost } from '@/utils/http'
	import formatToChineseDateTime from '@/utils/format/formatChineseDate'
	import { useUserStore } from '@/store'
	const userStore = useUserStore()
	const tab = ref(0)
	const tabs = ref(['洗脱烘', '烘干专用', '智能柜'])
	const selectedStore = ref<number | null>(null)
	const eventChild = ref(0)
	const handleChange = (index) => {
		eventChild.value = index.index
		Getlistdevices(shopid.value)
	}
	const shopid = ref('')
	const selectStore = (item : object, index : number) => {
		selectedStore.value = index;
		shopid.value = item.shop_id;
		Getlistdevices(item.shop_id);
	};
	onMounted(() => {
		Getlistorders()
	})
	// 判断是否应该显示GIF（机器运行中）
	const shouldShowGif = (item) => {
		return !isAvailable(item) && (isDryer(item) || isWasher(item))
	}
	// 判断是否是烘干专用机器
	const isDryer = (item) => {
		return item.device_type === 3
	}
	// 判断是否是洗脱烘机器
	const isWasher = (item) => {
		return item.device_type === 1 || item.device_type === 2
	}
	const isAvailable = (item) => {
		const availableTime = new Date(item.available_time).getTime();
		const currentTime = new Date().getTime();
		return availableTime <= currentTime;
	};
	// 添加倒计时相关逻辑
	const countdownTimers = ref<Record<string, number>>({});
	const formatCountdown = (item) => {
		if (isAvailable(item)) return '';

		const availableTime = new Date(item.available_time).getTime();
		const currentTime = new Date().getTime();
		const diff = availableTime - currentTime;

		if (diff <= 0) {
			clearInterval(countdownTimers.value[item.device_id]);
			delete countdownTimers.value[item.device_id];
			return '';
		}
		const hours = Math.floor(diff / (1000 * 60 * 60));
		const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
		const seconds = Math.floor((diff % (1000 * 60)) / 1000);
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
	};
	const startCountdown = (item) => {
		if (isAvailable(item)) return;
		if (!countdownTimers.value[item.device_id]) {
			countdownTimers.value[item.device_id] = setInterval(() => {
				// 触发更新
				Machine.value = [...Machine.value];
			}, 1000);
		}
	};
	const stopCountdown = (deviceId) => {
		if (countdownTimers.value[deviceId]) {
			clearInterval(countdownTimers.value[deviceId]);
			delete countdownTimers.value[deviceId];
		}
	};
	const Shoplist = ref([])
	const Getlistorders = async () => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const response = await httpGet(
				'/miniapp/list_shops/',
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code == 200) {
				Shoplist.value = response.data;
				if (Shoplist.value.length > 0) selectStore(Shoplist.value[0], 0)
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};
	const Machine = ref([])
	const Getlistdevices = async (item) => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			console.log(eventChild.value);
			const device = ref([])

			if (eventChild.value == 0) {
				device.value = [1, 2]
			} else if (eventChild.value == 1) {
				device.value = [3]
			} else {
				device.value = [5]
			}
			const response = await httpPost(
				'/miniapp/list_devices/',
				{
					"shop_id": item,
					"device_type": device.value
				},
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code) {
				// 清除旧的定时器
				Object.keys(countdownTimers.value).forEach(deviceId => {
					if (!response.data.some(item => item.device_id === deviceId)) {
						stopCountdown(deviceId);
					}
				});

				Machine.value = response.data;
				// 为每个不可用设备启动倒计时
				Machine.value.forEach(item => {
					if (!isAvailable(item)) {
						startCountdown(item);
					}
				});
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};

	// 组件卸载时清除所有定时器
	onUnmounted(() => {
		Object.values(countdownTimers.value).forEach(timer => {
			clearInterval(timer);
		});
		countdownTimers.value = {};
	});
</script>

<style scoped>
	:deep(.uni-scroll-view) {
		padding-bottom: 20rpx;
	}

	page {
		background-color: #f5f5f5;
	}

	:deep(.wd-tabs) {
		background-color: #f5f5f5 !important;
	}

	:deep(.wd-tabs__nav) {
		background-color: #f5f5f5 !important
	}
</style>

<style lang="scss" scoped>
	.flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.custom-shadow {
		background-color: white;
		color: black;
		width: 120rpx;
		height: 50rpx;
		opacity: 1;
		font-size: 12px;
		border-radius: 14.5px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border: none;

		&.selected-btn {
			background-color: black;
			color: white;
		}
	}

	.centerbox {
		width: 100%;
		height: 100%;

		.rechTop {
			width: 100%;
			height: 400rpx;
			position: relative;
			background-image: url('/static/images/vouchersTop.png');
			padding-top: constant(safe-area-inset-top);
			padding-top: env(safe-area-inset-top);
			background-size: 100% 100%;

			.ChooseTitle {
				padding-left: 40rpx;
				color: #fff;
				display: flex;
				height: 30rpx;
				font-size: 30rpx;
				margin-top: 100rpx;
				align-items: center;

				.Vertical {
					width: 7rpx;
					height: 100%;
					margin-right: 8rpx;
					background: rgba(255, 255, 255, 1);
				}
			}

			.imgTitele>image {
				margin-top: 60rpx;
				width: 360rpx;
				height: 40rpx;
			}

			.Store {
				position: absolute;
				bottom: -90rpx;
				left: 40rpx;
				right: 0rpx;

				.scroll-container {
					width: 100%;
					white-space: nowrap;

					.store-list {
						display: inline-flex;
						gap: 20rpx;
					}
				}

				.Storefront {
					padding: 30rpx;
					box-sizing: border-box;
					align-items: flex-end;
					background: rgba(25, 25, 25, 1);
					border-radius: 20rpx;
					display: inline-flex;
					justify-content: space-between;
					width: 360rpx;
					height: 105px;
					box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);

					&.selected {
						background: white;
						width: 360rpx;

						.store-name {
							color: black !important;
						}
					}

					.Store_right {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						align-items: flex-start;
						height: 100%;

						.store-name {
							font-size: 32rpx;
							font-weight: 700;
							color: white;
							margin-top: 0;
						}

						.custom-shadow {
							margin-left: -2rpx;
							margin-bottom: 0;
						}
					}

					.Store_left {
						img {
							width: 100rpx;
							height: 100rpx;
						}
					}
				}
			}

			.tabClss {
				margin-top: 240rpx;
				padding: 0 48rpx;

				.boxType {
					opacity: 1;
					padding: 20rpx 40rpx;
					margin-top: 20rpx;
					border-radius: 10px;
					background-color: white;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.boxType_left {
						display: flex;
						align-items: center;
						gap: 20rpx;

						img {
							width: 100rpx;
							height: 100rpx
						}

						.left_title {
							text-align: left;
							line-height: 1.2;

							img {
								width: 11px;
								height: 11px;
							}

							p {
								font-size: 32rpx;
								font-weight: 400;
								color: rgba(0, 0, 0, 1);
							}

							span {
								font-size: 24rpx;
								color: rgba(153, 153, 153, 1);
							}

							.spleft {
								margin-left: 10rpx;
							}
						}
					}

					.boxType_right {
						button {
							width: 150rpx;
							height: 60rpx;
							text-align: center;
							line-height: 60rpx;
							border-radius: 16px;
							font-size: 30rpx;
							color: white;
							border: none;

							&.available {
								background: rgba(74, 179, 75, 1);
							}

							&.in-use {
								background: rgba(153, 153, 153, 1);
							}

							&:disabled {
								opacity: 1;
							}
						}
					}
				}
			}
		}
	}
</style>